import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { ProgressProps } from 'element-plus'
import {
  getProjectDetail,
  getProjectMembers,
  getProjectActivities
} from '@/api/project'
import { PROJECT_MEMBER_ROLES } from '@/types/project'
import { getTaskList } from '@/api/task'
import { getDefects } from '@/api/defect'
import { getRequirements, type RequirementResponse } from '@/api/requirements'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { calculateProjectProgress } from '@/utils/projectProgress'

type ProgressStatus = NonNullable<ProgressProps['status']>

// 需求状态分类 - 从状态管理系统动态获取
const { requirementStates } = useRequirementStates()

// 动态获取完成状态（包含"完成"、"已完成"、"已实现"等关键词）
const getRequirementCompletedStatuses = computed(() => {
  const completedStatuses = new Set<string>()
  requirementStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('完成') || name.includes('已完成') || name.includes('已实现') ||
        code.includes('completed') || code.includes('done') || code.includes('implemented')) {
      completedStatuses.add(state.code)
    }
  })
  return completedStatuses
})

// 动态获取活跃状态（包含"进行中"、"进行"、"测试中"等关键词）
const getRequirementActiveStatuses = computed(() => {
  const activeStatuses = new Set<string>()
  requirementStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('进行中') || name.includes('进行') || name.includes('测试中') || name.includes('评审中') ||
        code.includes('in_progress') || code.includes('testing') || code.includes('review')) {
      activeStatuses.add(state.code)
    }
  })
  return activeStatuses
})

// 动态获取待处理状态（包含"草稿"、"新建"、"待审核"、"已批准"等关键词）
const getRequirementPendingStatuses = computed(() => {
  const pendingStatuses = new Set<string>()
  requirementStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('草稿') || name.includes('新建') || name.includes('待审核') || name.includes('已批准') ||
        code.includes('draft') || code.includes('new') || code.includes('review') || code.includes('approved')) {
      pendingStatuses.add(state.code)
    }
  })
  return pendingStatuses
})

// 任务状态分类 - 从状态管理系统动态获取
import { useTaskStates } from '@/composables/useTaskStates'

const { taskStates } = useTaskStates()

// 动态获取完成状态（包含"完成"、"已完成"、"done"等关键词）
const getTaskCompletedStatuses = computed(() => {
  const completedStatuses = new Set<string>()
  taskStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('完成') || name.includes('已完成') ||
        code.includes('completed') || code.includes('done') || code.includes('finished')) {
      completedStatuses.add(state.code)
    }
  })
  return completedStatuses
})

// 动态获取活跃状态（包含"进行中"、"进行"、"reviewing"等关键词）
const getTaskActiveStatuses = computed(() => {
  const activeStatuses = new Set<string>()
  taskStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('进行中') || name.includes('进行') || name.includes('审核中') || name.includes('处理中') ||
        code.includes('in_progress') || code.includes('reviewing') || code.includes('processing') || code.includes('doing')) {
      activeStatuses.add(state.code)
    }
  })
  return activeStatuses
})

// 动态获取待处理状态（包含"待处理"、"待办"、"pending"等关键词）
const getTaskPendingStatuses = computed(() => {
  const pendingStatuses = new Set<string>()
  taskStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('待处理') || name.includes('待办') || name.includes('新建') ||
        code.includes('pending') || code.includes('todo') || code.includes('backlog') || code.includes('planned') || code.includes('new')) {
      pendingStatuses.add(state.code)
    }
  })
  return pendingStatuses
})

// 缺陷状态分类 - 从状态管理系统动态获取
import { useDefectStates } from '@/composables/useDefectStates'

const { defectStates } = useDefectStates()

// 动态获取打开状态（包含"新建"、"已分配"、"进行中"、"重新打开"等关键词）
const getDefectOpenStatuses = computed(() => {
  const openStatuses = new Set<string>()
  defectStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('新建') || name.includes('新') || name.includes('已分配') || name.includes('分配') ||
        name.includes('进行中') || name.includes('进行') || name.includes('重新打开') || name.includes('重开') ||
        code.includes('new') || code.includes('open') || code.includes('assigned') ||
        code.includes('in_progress') || code.includes('reopened')) {
      openStatuses.add(state.code)
    }
  })
  return openStatuses
})

// 动态获取已解决状态（包含"已解决"、"解决"、"已验证"、"验证"等关键词）
const getDefectResolvedStatuses = computed(() => {
  const resolvedStatuses = new Set<string>()
  defectStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('已解决') || name.includes('解决') || name.includes('已验证') || name.includes('验证') ||
        code.includes('resolved') || code.includes('verified')) {
      resolvedStatuses.add(state.code)
    }
  })
  return resolvedStatuses
})

// 动态获取已关闭状态（包含"已关闭"、"关闭"等关键词）
const getDefectClosedStatuses = computed(() => {
  const closedStatuses = new Set<string>()
  defectStates.value.forEach(state => {
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('已关闭') || name.includes('关闭') ||
        code.includes('closed')) {
      closedStatuses.add(state.code)
    }
  })
  return closedStatuses
})

export function useProjectDetail() {
  const route = useRoute()
  const router = useRouter()

  const loading = ref(false)
  const tasksLoading = ref(false)
  const defectsLoading = ref(false)
  const requirementsLoading = ref(false)
  const activeTab = ref('tasks')
  const projectId = computed(() => route.params.id as string)

  const project = ref<Record<string, any>>({
    id: '',
    name: '',
    description: '',
    category: 'other',
    priority: 'medium',
    status: 'planning',
    start_date: '',
    end_date: '',
    is_public: false,
    created_by: '',
    created_by_name: '',
    created_at: '',
    updated_at: '',
    task_count: 0,
    completed_task_count: 0,
    active_task_count: 0,
    overdue_task_count: 0,
    estimated_hours: 0,
    budget: 0,
    tags: [],
    members: [],
    requirement_count: 0,
    requirement_completed_count: 0,
    requirement_active_count: 0,
    requirement_pending_count: 0,
    defect_count: 0
  })

  const projectTasks = ref<any[]>([])
  const projectDefects = ref<any[]>([])
  const projectRequirements = ref<RequirementResponse[]>([])
  const projectMembers = ref<any[]>([])

  const recentActivities = ref<any[]>([])

  const taskPreviewList = computed(() => projectTasks.value.slice(0, 5))
  const defectPreviewList = computed(() => projectDefects.value.slice(0, 5))
  const requirementPreviewList = computed(() => projectRequirements.value.slice(0, 5))

  const projectTaskCount = computed(() => project.value.task_count || projectTasks.value.length)
  const completedTaskCount = computed(() =>
    project.value.completed_task_count || projectTasks.value.filter(task => getTaskCompletedStatuses.value.has(task.status)).length
  )
  const activeTaskCount = computed(() =>
    project.value.active_task_count || projectTasks.value.filter(task => getTaskActiveStatuses.value.has(task.status)).length
  )
  const pendingTaskCount = computed(() =>
    project.value.task_count
      ? project.value.task_count - (project.value.completed_task_count || 0) - (project.value.active_task_count || 0)
      : projectTasks.value.filter(task => getTaskPendingStatuses.value.has(task.status)).length
  )

  const projectDefectCount = computed(() => project.value.defect_count || projectDefects.value.length)
  const openDefectCount = computed(() =>
    projectDefects.value.filter(defect => getDefectOpenStatuses.value.has(defect.status)).length
  )
  const resolvedDefectCount = computed(() =>
    projectDefects.value.filter(defect => getDefectResolvedStatuses.value.has(defect.status)).length
  )
  const closedDefectCount = computed(() =>
    projectDefects.value.filter(defect => getDefectClosedStatuses.value.has(defect.status)).length
  )

  const projectRequirementCount = computed(() =>
    project.value.requirement_count || projectRequirements.value.length
  )

  const completionPercentage = computed(() => {
    // 使用统一的进度计算函数，与后端逻辑保持一致
    
    // 获取已解决的缺陷数量
    const resolvedDefectCount = project.value.resolved_defect_count || 
      projectDefects.value.filter(defect => getDefectResolvedStatuses.value.has(defect.status)).length
    
    return calculateProjectProgress({
      requirement_count: projectRequirementCount.value,
      requirement_completed_count: project.value.requirement_completed_count || completedRequirementCount.value,
      task_count: projectTaskCount.value,
      completed_task_count: project.value.completed_task_count || completedTaskCount.value,
      defect_count: projectDefectCount.value,
      resolved_defect_count: resolvedDefectCount,
      project_status: project.value.status,
      start_date: project.value.start_date,
      end_date: project.value.end_date,
      progress: project.value.progress
    })
  })

  const progressColor = computed(() => {
    const percent = completionPercentage.value
    if (percent >= 100) return '#67c23a'
    if (percent >= 60) return '#409eff'
    if (percent >= 30) return '#e6a23c'
    return '#f56c6c'
  })

  const completionStatus = computed<ProgressStatus>(() =>
    completionPercentage.value >= 100 ? 'success' : ''
  )

  const completedRequirementCount = computed(() =>
    project.value.requirement_completed_count ||
    projectRequirements.value.filter(r => getRequirementCompletedStatuses.value.has(r.status)).length
  )

  const activeRequirementCount = computed(() =>
    project.value.requirement_active_count ||
    projectRequirements.value.filter(r => getRequirementActiveStatuses.value.has(r.status)).length
  )

  const pendingRequirementCount = computed(() =>
    project.value.requirement_pending_count ||
    projectRequirements.value.filter(r =>
      getRequirementPendingStatuses.value.has(r.status) ||
      (!getRequirementCompletedStatuses.value.has(r.status) && !getRequirementActiveStatuses.value.has(r.status))
    ).length
  )

  // 动态获取"通过"状态代码
  const fetchProjectDetail = async () => {
    try {
      const response = await getProjectDetail(projectId.value)
      if (response.data) {
        project.value = { ...project.value, ...response.data }
      }
    } catch (error) {
      ElMessage.error('获取项目详情失败')
    }
  }

  const roleLabelMap = PROJECT_MEMBER_ROLES.reduce<Record<string, string>>((acc, item) => {
    acc[item.value] = item.label
    return acc
  }, {})

  const normalizeMember = (member: Record<string, any>) => {
    const normalizedRole = member.role || 'viewer'
    const userId = member.user_id ?? member.id ?? ''
    const name =
      member.name ||
      member.user_name ||
      member.username ||
      member.email?.split?.('@')?.[0] ||
      '未命名成员'

    return {
      ...member,
      id: member.id ?? userId,
      user_id: String(userId),
      name,
      user_name: member.name || member.user_name || member.username || name,
      username: member.username || member.user_name || name,
      user_avatar: member.avatar || member.user_avatar || '',
      avatar: member.avatar || member.user_avatar || '',
      email: member.email || member.user_email || '',
      user_email: member.email || member.user_email || '',
      role: normalizedRole,
      role_label: member.role_label || roleLabelMap[normalizedRole] || '未知角色',
      permissions: member.permissions ?? [],
      joined_at: member.joined_at,
      is_active: member.is_active
    }
  }

  const fetchProjectMembers = async () => {
    try {
      const response = await getProjectMembers(projectId.value)
      const payload = response?.data
      // getProjectMembers 返回 ApiResponse<ProjectMember[]>，所以 data 应该是数组
      // 但为了兼容性，也检查 payload?.members 的情况
      const membersArray = Array.isArray(payload)
        ? payload
        : (payload && typeof payload === 'object' && 'members' in payload && Array.isArray((payload as any).members))
          ? (payload as any).members
          : []

      projectMembers.value = membersArray.map(normalizeMember)
    } catch (error) {
      ElMessage.error('获取项目成员失败')
      projectMembers.value = []
    }
  }

  const fetchProjectTasks = async () => {
    try {
      tasksLoading.value = true
      const response = await getTaskList({ project_id: projectId.value, page: 1, size: 5 })
      projectTasks.value = response.items || []
      if (typeof response.total === 'number') {
        project.value.task_count = response.total
      }
    } catch (error) {
      ElMessage.error('获取项目任务失败')
    } finally {
      tasksLoading.value = false
    }
  }

  const fetchProjectDefects = async () => {
    try {
      defectsLoading.value = true
      const response = await getDefects({ project_id: projectId.value, page: 1, size: 5 })
      projectDefects.value = response.items || []
      if (typeof response.total === 'number') {
        project.value.defect_count = response.total
      }
    } catch (error) {
      ElMessage.error('获取项目缺陷失败')
    } finally {
      defectsLoading.value = false
    }
  }

  const fetchProjectRequirements = async () => {
    try {
      requirementsLoading.value = true
      const response = await getRequirements({ project_id: projectId.value, limit: 5 })
      projectRequirements.value = response.data ?? []
      const maybeTotal = (response as any)?.pagination?.total || (response as any)?.total
      if (typeof maybeTotal === 'number') {
        project.value.requirement_count = maybeTotal
      }
    } catch (error) {
      ElMessage.error('获取项目需求失败')
    } finally {
      requirementsLoading.value = false
    }
  }

  const fetchProjectActivities = async () => {
    try {
      const response = await getProjectActivities(projectId.value, { page: 1, size: 10 })
      const payload = response?.data
      // getProjectActivities 返回 ApiResponse<{ items: any[]; ... }>，所以 data 应该是 { items: ... }
      // 但为了兼容性，也检查其他格式
      const items = (payload && typeof payload === 'object' && 'items' in payload && Array.isArray((payload as any).items))
        ? (payload as any).items
        : Array.isArray(payload)
          ? payload
          : []

      recentActivities.value = items.map((item: any) => ({
        id: item.id || item._id || Math.random().toString(36).slice(2),
        user: item.user_name || item.user || item.operator || '未知用户',
        action: item.action || item.title || '执行了操作',
        description: item.description || item.detail || '',
        type: item.type || item.target_type || 'default',
        time: item.created_at ? new Date(item.created_at).getTime() : Date.now()
      }))
    } catch (error) {
      ElMessage.error('获取最近活动失败')
      recentActivities.value = []
    }
  }

  const loadProjectData = async () => {
    loading.value = true
    try {
      await fetchProjectDetail()
      await Promise.all([
        fetchProjectMembers(),
        fetchProjectTasks(),
        fetchProjectDefects(),
        fetchProjectRequirements(),
        fetchProjectActivities()
      ])
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    tasksLoading,
    defectsLoading,
    requirementsLoading,
    activeTab,
    projectId,
    project,
    projectTasks,
    projectDefects,
    projectRequirements,
    projectMembers,
    recentActivities,
    taskPreviewList,
    defectPreviewList,
    requirementPreviewList,
    projectTaskCount,
    completedTaskCount,
    activeTaskCount,
    pendingTaskCount,
    projectDefectCount,
    openDefectCount,
    resolvedDefectCount,
    closedDefectCount,
    projectRequirementCount,
    completionPercentage,
    progressColor,
    completionStatus,
    completedRequirementCount,
    activeRequirementCount,
    pendingRequirementCount,
    loadProjectData,
    router
  }
}

